<template>
  <el-affix :offset="0" style="box-shadow: 0 3px 3px 0 rgba(0, 0, 0, 0.1);">
    <el-row style="background-color: #f6f6f1">
      <el-col class="hidden-sm-and-down" :span="6">
        <h1
          style="margin-left: 20px; color: #53a8ff; float: right; margin-right: 30px;cursor: pointer"
          @click="returnTo"
        >
          视频搜索
        </h1>
      </el-col>
      <el-col
        :xs="16"
        :sm="12"
        :md="12"
        :lg="12"
        :xl="12"
        style="align-self: center"
      >
        <el-input
          v-model="search_str"
          placeholder="请输入内容"
          :trigger-on-focus="false"
          style="width: 100%; float: left;padding: 17px 10px 18px 10px"
          @keyup.enter="searchVideo"
        >
          <template #append>
            <el-button icon="el-icon-search" @click="searchVideo"></el-button>
          </template>
        </el-input>
      </el-col>
      <el-col
        :xs="8"
        :sm="12"
        :md="6"
        :lg="6"
        :xl="6"
        style="align-self: center"
      >
        <div style="padding-left: 20px">
          <el-radio v-model="search_type" label="1">普通搜索</el-radio>
          <el-radio v-model="search_type" label="2">关键词搜索</el-radio>
        </div>
      </el-col>
    </el-row>
  </el-affix>
  <router-view></router-view>
  <el-container>
    <el-aside width="10%"></el-aside>
    <el-main
      v-loading="loading"
      v-if="$router.currentRoute.value.name === 'Video'"
    >
      <el-row>
        <el-col
          :lg="img_length"
          v-for="(video, index) in videos"
          :key="index"
          v-bind="img_length"
          :offset="img_length !== 24 && index % 5 !== 0 ? 1 : 0"
          style="margin-top: 10px"
        >
          <el-card
            :body-style="{ padding: '5px', height: '220px' }"
            v-show="window_length < 767 || window_length >= 1200"
            @click="to_detail(video.video_name, video.video_src)"
            style="cursor: pointer"
          >
            <div style="height: 120px">
              <el-image :src="get_pic(imageList[index])" :fit="fit"></el-image>
            </div>
            <div style="text-align: center">
              <span>视频名称：《{{ video.video_name }}》</span>
            </div>
          </el-card>

          <el-card
            :body-style="{ padding: '5px', height: '430px' }"
            v-show="window_length >= 1000 && window_length < 1200"
            @click="to_detail(video.video_name, video.video_src)"
            style="cursor: pointer"
          >
            <div style="height: 350px">
              <el-image
                :src="get_pic(imageList[index])"
                style="background-position: center"
                :fit="fit"
              ></el-image>
            </div>
            <div style="text-align: center">
              <span>视频名称：《{{ video.video_name }}》</span>
            </div>
          </el-card>

          <el-card
            :body-style="{ padding: '5px', height: '450px' }"
            v-show="window_length >= 767 && window_length < 1000"
            @click="to_detail(video.video_name, video.video_src)"
            style="cursor: pointer"
          >
            <div style="height: 365px">
              <el-image
                :src="get_pic(imageList[index])"
                style="background-position: center"
                :fit="fit"
              ></el-image>
            </div>
            <div style="text-align: center">
              <span>视频名称：《{{ video.video_name }}》</span>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </el-main>
    <el-aside width="10%"></el-aside>
  </el-container>
</template>

<script>
import { request } from "@/network/request";
import { ElMessage } from "element-plus";

export default {
  name: "Video",
  data() {
    return {
      search_str: "",
      search_type: "2",
      bookInfo: [],
      com_bookInfo: [],
      all_bookInfo: [],
      current_page: 1,
      page_size: 5,
      loading: false,
      timeout: null,
      results: [],
      fit: "fill",
      img_length: 4,
      window_length: 0,
      curSrc: "",
      videos: [], //存放video对象
      videoList: [],
      imageList: [],
      data: [],
      srcList: []
    };
  },
  methods: {
    searchVideo() {
      let url = "";
      if (this.search_type === "1") {
        url = "/searchVideo/searchByname";
      } else if (this.search_type === "2") {
        url = "/searchVideo/searchByname";
      }
      if (this.search_str === "") {
        ElMessage({
          message: "请输入搜索内容！",
          duration: 700,
          type: "warning"
        });
      } else if (url !== "") {
        this.loading = true;
        request({
          url: url,
          method: "post",
          data: {
            searchList: this.search_str.split(/[,\s.;，；。]+/)
          }
        })
          .then(res => {
            // console.log(res);
            if (res.data.code === "200") {
              this.videos = res.data.result;
              this.videoList = [];
              this.imageList = [];
              for (let i in this.videos) {
                this.videoList.push({
                  src: "/video/" + this.videos[i].video_src
                });
              }
              this.getVideoposter();
              this.$router.push({ name: "Video" });
            } else if (res.data.code === "400") {
              ElMessage({
                message: res.data.code + " " + res.data.msg,
                type: "error",
                duration: 800,
                showClose: true
              });
            }
          })
          // eslint-disable-next-line no-unused-vars
          .catch(err => {
            console.log(err);
            ElMessage.error("请求超时！");
          })
          .finally(() => {
            this.loading = false;
          });
      }
    },
    get_pic(src) {
      return src;
    },
    to_detail(videoName, videoSrc) {
      // console.log(bookId);
      this.$router.push({
        name: "VideoDetail",
        params: { videoName: videoName, videoSrc: videoSrc }
      });
    },
    returnTo() {
      // console.log("click");
      this.$router.push({ name: "Video" });
      this.bookInfo = [];
      this.com_bookInfo = [];
    },
    getVideoposter() {
      // let self = this;
      this.videoList.forEach(item => {
        // console.log("videoitem:", item);
        let video = document.createElement("video");
        video.setAttribute("crossOrigin", "Anonymous");
        video.src = item.src;
        //如果不设置currentTime，画出来的图片是空的
        video.currentTime = 20;
        video.onloadeddata = loadedmetadata;
        // console.log("video", video);
        let that = this;
        function loadedmetadata(e) {
          let canvas = document.createElement("canvas");
          let vWidth = e.path[0].videoWidth;
          let vHeight = e.path[0].videoHeight;
          //判断视频的高度和宽度
          //画布的大小，由设置的视频显示的大小决定，以免画布太大，画的图片太大，浪费资源，这里设置显示视频盒子为width:140px，height:140px;
          //设置倍数是rate，倍数越大画图的图片越大，加载速度越慢
          //https://www.w3school.com.cn/html5/canvas_drawimage.asp
          // let rate = 4;
          canvas.width = 140 * 4;
          canvas.height = ((vHeight * 140) / vWidth) * 4;
          canvas
            .getContext("2d")
            .drawImage(video, 0, 0, canvas.width, canvas.height);
          let url = canvas.toDataURL("image/png", 1);
          // console.log("url", url);
          //显示背景图片的大小，保证在不压缩图片的情况下，背景图片能铺满
          // let widthBg, heightBg;
          // if (vWidth < vHeight) {
          //   widthBg = 140;
          //   heightBg = vHeight * 140 / vWidth;
          // } else {
          //   widthBg = vWidth * 140 / vHeight;
          //   heightBg = 140;
          // }

          // self.$set(item, item+'.poster', url);
          // self.$set(item, item+'.width', widthBg)
          // self.$set(item, item+'.height', heightBg)
          that.imageList.push(url);
          // console.log(self);
        }
      });
    }
  },
  created() {
    this.window_length = window.screen.width;
    if (window.screen.width >= 1200) {
      this.img_length = 4;
    } else {
      this.img_length = 24;
    }
    this.$notify({
      title: "欢迎回来！",
      message: "🤗🤗",
      position: "bottom-left",
      duration: 1500
    });
    request({
      url: "/searchVideo/searchAll",
      method: "post"
    })
      .then(res => {
        // console.log(res);
        if (res.data.code === "200") {
          this.videos = res.data.result;
          for (let i in this.videos) {
            this.videoList.push({ src: "/video/" + this.videos[i].video_src });
          }
          this.getVideoposter();
        } else if (res.data.code === "400") {
          ElMessage.error(res.data.msg);
        }
      })
      // eslint-disable-next-line no-unused-vars
      .catch(err => {
        console.log(err);
        ElMessage.error("请求超时！");
      });
  },
  computed: {}
};
//防止页面后退
history.pushState(null, null, document.URL);
window.addEventListener("popstate", function() {
  history.pushState(null, null, document.URL);
});
</script>
